package cn.edu.sgu.www.mhxysy.redis.repository.impl;

import cn.edu.sgu.www.mhxysy.consts.RedisKeyPrefixes;
import cn.edu.sgu.www.mhxysy.entity.system.Email;
import cn.edu.sgu.www.mhxysy.redis.RedisUtils;
import cn.edu.sgu.www.mhxysy.redis.repository.RedisRepository;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author 沐雨橙风ιε
 * @version 1.0
 */
@Slf4j
@Component
public class EmailRepository implements RedisRepository {

    private final RedisUtils redisUtils;

    public EmailRepository(RedisUtils redisUtils) {
        this.redisUtils = redisUtils;
    }

    @Override
    public void put(String userId, Object value) {
        String key = RedisKeyPrefixes.PREFIX_EMAIL + userId;

        redisUtils.set(key, JSON.toJSONString(value));
    }

    @Override
    public List<Email> selectById(String userId) {
        String key = RedisKeyPrefixes.PREFIX_EMAIL + userId;
        String value = redisUtils.get(key);

        if (value != null) {
            log.debug("命中缓存{}", key);

            return JSON.parseArray(value, Email.class);
        }

        return null;
    }

    @Override
    public void deleteById(String userId) {
        redisUtils.delete(RedisKeyPrefixes.PREFIX_EMAIL + userId);
    }

}